/*
 * @Descripttion: 
 * @Author: yuxi
 * @Date: 2024-03-04 18:14:28
 * @LastEditors: yuxi
 * @LastEditTime: 2024-05-15 15:57:39
 */
(function () {
  $('#refresh').click(() => {
    refresh()
  })
  $('#view').click(async () => {
    await view()
  })
  $('#clear').click(() => {
    clear()
  })
  $('#notice').click(() => {
    chrome.tabs.create({
      url: "https://www.luogu.com"
    })
  })
  chrome.tabs.query({
    active: true,
    currentWindow: true
  }, (tabs) => {
    if (tabs[0].url.indexOf("luogu.com") >= 0) {
      $('#refresh').show()
      $('#clear').show()
      $('#view').show()
      $('#notice').hide()
    }
  })
})()
var NOLOGIN = '用户未登录，请登录后操作！'

function getUid () {
  return new Promise((resolve, reject) => {
    chrome.cookies.get({
      url: "https://www.luogu.com.cn",
      name: "_uid"
    }, function (cookie) {
      if (!cookie.value || cookie.value == '0') {
        notice(NOLOGIN)
      } else {
        resolve(cookie.value)
      }
    })
  })
}

function notice (message) {
  chrome.notifications.create("notlogin11" + new Date().getTime(), {
    type: "basic",
    iconUrl: "../images/icon.png",
    title: "洛谷辅助插件提示",
    message: message
  })
  // alert(message)
}
async function clear () {
  const uid = await getUid()
  const key = "LuoguResult_" + uid
  chrome.storage.local.remove(key, () => {
    notice('清理完成')
  })
}

function getSavedLuoguResult () {
  return new Promise((reslove, reject) => {
    chrome.cookies.get({
      url: "https://www.luogu.com.cn",
      name: "_uid"
    }, function (cookie) {
      if (!cookie.value || cookie.value == '0') {
        notice(NOLOGIN)
        reject(new Error(NOLOGIN))
      }
      const key = "LuoguResult_" + cookie.value
      chrome.storage.local.get(key, function (savedResult) {
        savedResult = savedResult ? savedResult[key] ? JSON.parse(savedResult[key]) : [] : []
        reslove(savedResult)
      })
    })
  })
}

async function refresh () {
  chrome.runtime.sendMessage({ action: "refreshLuoguResult" }, (response) => {
    // 3. Got an asynchronous response with the data from the service worker
    console.log('received user data', response);
  });
}
async function view () {
  const uid = await getUid()
  chrome.runtime.sendMessage({ action: "jumpToView", uid }, (response) => {
    // 3. Got an asynchronous response with the data from the service worker
    console.log('received user data', response);
  });
}



function removeMask () {
  let mask = document.getElementById('luogu_mask')
  mask && mask.remove()
}
function showMask () {
  let mask = document.createElement('div')
  mask.style.position = "fixed"
  mask.style.left = 0
  mask.style.right = 0
  mask.style.top = 0
  mask.style.bottom = 0
  mask.style.zIndex = 1000
  mask.style.textAlign = "center"
  mask.style.fontSize = "24px"
  mask.style.color = "white"
  mask.style.display = "flex"
  mask.style.alignItems = "center"
  mask.style.justifyContent = "center"
  mask.id = "luogu_mask"
  mask.innerText = "加载洛谷数据中，请稍后..."
  mask.style.backgroundColor = "rgba(0,0,0,0.4)"
  document.body.appendChild(mask)
}
function getAllResult (uid, pid = "", records = [], page = 1, savedCount, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function () {
    // 通信成功时，状态值为4
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        let res = JSON.parse(xhr.responseText)
        records = records.concat(res.currentData.records.result)
        if (res.currentData.records.count > records.length + savedCount) {
          getAllResult(uid, pid, records, page + 1, savedCount, callback)
        } else {
          callback({ records, total: res.currentData.records.count })
        }

      } else {
        console.error(xhr.statusText);
      }
    }
  };
  xhr.onerror = function (e) {
    console.error(xhr.statusText);
  };
  xhr.open('GET', `http://localhost:18081/`, true);
  xhr.send(null);
}

function request (action, tabId) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function () {
    // 通信成功时，状态值为4
    if (xhr.readyState === 4) {

    }
  };
  xhr.onerror = function (e) {
    console.error(xhr.statusText);
  };
  xhr.open('GET', `http://localhost:18081/?action=${action}&tabId=${tabId}`, true);
  xhr.send(null);
}

// chrome.tabs.onCreated.addListener(
//   (tabs) => {
//     console.log('content tabs', tabs)
//     request('create', tabs.tab.id)
//   },
// )

// chrome.tabs.onRemoved.addListener(
//   (tabs) => {
//     console.log('content tabs', tabs)
//     request('remove', tabs)
//   },
// )